SecurityContextHolder

SecurityContextHolder是一个基本对象,为使用者提供全局的SecurityContext,SecurityContextHolder 使用ThreadLocal保存这些信息。这意味着the security context总是可用于同一执行线程中的方法,即使安全上下文没有明确传递给这些方法的参数

The most fundamental object is SecurityContextHolder. This is where we store details of the present security context of the application, which includes details of the principal currently using the application. By default the SecurityContextHolder uses a ThreadLocal to store these details,

which means that the security context is always available to methods in the same thread of execution,

even if the security context is not explicitly passed around as an argument to those methods. Using a

ThreadLocal in this way is quite safe if care is taken to clear the thread after the present principal's

request is processed. Of course, Spring Security takes care of this for you automatically so there is no

need to worry about it.

ThreadLocal不是所有的情况都适用,可以配置ThreadLocal的策略。

org.springframework.security.core.context.SecurityContextHolder

    public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL";
    public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL";
    public static final String MODE_GLOBAL = "MODE_GLOBAL";

Some applications aren't entirely suitable for using a ThreadLocal, because of the specific way they work with threads. For example, a Swing client might want all threads in a Java Virtual Machine to use the same security context. SecurityContextHolder can be configured with a strategy on startup to specify how you would like the context to be stored. For a standalone application you would use the SecurityContextHolder.MODE_GLOBAL strategy. Other applications might want to have threads spawned by the secure thread also assume the same security identity. This is achieved by using SecurityContextHolder.MODE_INHERITABLETHREADLOCAL. You can change the mode from the default SecurityContextHolder.MODE_THREADLOCAL in two ways. The first is to set a system property, the second is to call a static method on SecurityContextHolder. Most applications won't need to change from the default, but if you do, take a look at the JavaDocs for SecurityContextHolder to learn more.

整体UML如下:

1、SecurityContextHolder 通过策略模式获取到SecurityContext

    public static SecurityContext getContext() {
        return strategy.getContext();
    }

2、SecurityContext中可以获取到Authentication

Authentication getAuthentication();

3、Authentication,主要负责候住两方面信息,一个是当前用户的详细信息(Principal、UserDetails),一个是用户鉴权时需要的信息。

4、GrantedAuthority,提供当前用户(UserDetails)所获得的系统范围内的授权。

http://www.dewafer.com/2016/10/01/dive-into-spring-security/

results matching ""

    No results matching ""